package v2ray

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/application/v2ray"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
)

type SetInboundVMessRequest struct {
	BaseBoundRequest
	BaseInboundRequest

	DisableInsecureEncryption bool                      `json:"disable_insecure_encryption" validate:"optional" binding:"omitempty"` // 是否禁用不安全的加密方式
	Clients                   []SetInboundVMessClient   `json:"clients" validate:"required" binding:"required,min=1,dive"`           // 客户端配置
	StreamSettings            BaseStreamSettingsRequest `json:"stream_settings" validate:"optional" binding:"omitempty,dive"`        // 传输配置
}

type SetInboundVMessClient struct {
	Id    string `json:"id" validate:"required" binding:"required,min=16,max=64"` // ID
	Email string `json:"email" validate:"optional" binding:"omitempty,email"`     // 邮件地址
	Level int    `json:"level" validate:"optional" binding:"omitempty,min=0"`     // 用户级别，建设设置为0
}

func (cls *V2ray) SetInboundVMess(c *gin.Context) (int, any, error) {
	var body = SetInboundVMessRequest{}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	var clients []*application.V2rayVMessClient
	for _, client := range body.Clients {
		clients = append(clients, &application.V2rayVMessClient{Id: client.Id, Email: client.Email, Level: client.Level})
	}

	var ctx = context.Background()

	var protocol, err = v2ray.NewVMessInbound(body.Id, body.Tag, body.InboundListen, body.InboundPort, body.DisableInsecureEncryption, clients, body.StreamSettings.build())
	if nil != err {
		return response.InvalidRequest, nil, err
	}

	if err := cls.v2ray.SetInbound(ctx, protocol.Id, protocol); nil != err {
		return response.Unknown, nil, err
	}

	// 应用配置
	if err := cls.v2ray.ApplyConfig(ctx); nil != err {
		return response.Unknown, nil, err
	}

	return response.Ok, nil, nil
}
